var _avatar = {
	SWFUpload: null,
	file: null,
	scale: {w: 0, h: 0, width: 0, height: 0, src: null},
	thumbs: {large: 128, middle: 64, thumb: 32, small: 16},
	uploading: false,
	setting: {
		upload_form: null,
		upload_preview: null
	},
	language: {
		running: 'avatar is uploading, please wait for a moment.',
		onlyforone: 'only for one',
		uploading: 'uploading',
		posting: 'posting'
	},
	swfu: {
		file_post_name: 'file',
		flash_url: 'swfupload.swf',
		upload_url: 'upload',
		post_params: {},
		file_size_limit : "8 MB",
		file_types : "*.jpg;*.png",
		file_types_description : "Web Image Files",
		file_upload_limit : 0,
		file_queue_limit : 0,
		http_success : [201, 202],
		debug: false,
		button_width: "120",
		button_height: "24",
		button_action : SWFUpload.BUTTON_ACTION.SELECT_FILES,
		button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
		button_placeholder_id: "uploadPlaceHolder",
		button_text: '<span class="theFont">SELECT IMAGE FILE(s)</span>',
		button_text_style: ".theFont{font-size:14;color:#FFFFFF;}",
		button_cursor: SWFUpload.CURSOR.HAND,
		button_text_left_padding: 3,
		button_text_top_padding: 3,
		swfupload_loaded_handler: function() {},
		file_dialog_complete_handler: function(numFilesSelected, numFilesQueued, totalNumOfFile) {
			if(_avatar.uploading == true) {
				_avatar.error(_avatar.language.running, 0);
				return false;
			}
			if(numFilesSelected > 1) {
				_avatar.error(_avatar.language.onlyforone, 0);
				return false;
			}
			_avatar.doUpload();
		},
		file_queued_handler: function(file) {
			_avatar.file  = file;
		},
		file_queue_error_handler: function(file, code, msg) {
			_avatar.error(msg, code);
		},
		queue_complete_handler: function(numFilesUploaded) {
			//alert('3'); //暂无用处
		},
		upload_start_handler: function(file) {
			_avatar.uploading = true;
			//alert('4');
		},
		upload_progress_handler: function(file, bytes, total) {
			var percent = Math.round(bytes / total) * 100;
			$('#percentValue').text(percent + '%');
			$('#percentBar').css({'width': percent + '%'});
			if(percent >= 100) {
				$('#statusId').text('Processing ..');
			}
		},
		upload_success_handler : function(file, data, response) {
			try {
				var json = JSON.parse(data);
				if(json.status == false || json.status == 0) {
					throw json.message;
				}
				_avatar.scale.width = json.file.width;
				_avatar.scale.height = json.file.height;
				_avatar.scale.src = _avatar.setting.upload_preview + '?r=' + Math.random();
				this.uploading = false;
				$('#processIcon').hide();
				$('#avatarPhoto').html('<img id="_avatarPhoto" src="' + _avatar.scale.src + '" />');
				$('#_avatarPhoto').load(function() {
					_avatar.scale.w = $(this).width();
					_avatar.scale.h = $(this).height();					
					_avatar.ps.hide();
					var mt = ($('#original').height() - _avatar.scale.h) / 2;
					var ml = ($('#original').width() - _avatar.scale.w) / 2;
					$('#avatarPhoto').css({'margin-top': mt + 'px', 'margin-left': ml + 'px'});
					$(this).Jcrop(_avatar.jcrop, function(){$('#saveButton').show();});
				});
			} catch (e) {
				var msg = typeof(e) == 'string' ? e : e.message;
				_avatar.error(msg, 1);
			}
		},
		upload_error_handler : function(file, code, msg) {
			_avatar.error(msg, code);
		},
		upload_complete_handler : function(file) {
			_avatar.uploading = false;
			//alert('end');
		}
	},
	jcrop: {
		aspectRatio: 1/1,
		minSize: [128, 128],
		setSelect: [10, 10, 138, 138],
		onRelease: function() {},
		onChange: function(coords) {
			var px = _avatar.scale.w / _avatar.scale.width;
			for(var id in _avatar.thumbs) {
				var rx = _avatar.thumbs[id] / coords.w;
				$('#' + id + ' img').attr('src', _avatar.scale.src).css({
					width: Math.round(px * _avatar.scale.width * rx) + 'px',
					height: Math.round(px * _avatar.scale.height * rx) + 'px',
					marginLeft: '-' + Math.round(rx * coords.x) + 'px',
					marginTop: '-' + Math.round(rx * coords.y) + 'px'
				});
			}
			$('input#crop-p').val(px);
			$('input#crop-x').val(coords.x);
			$('input#crop-y').val(coords.y);
			$('input#crop-w').val(coords.w);
			$('input#crop-h').val(coords.h);
		},
		onSelect: function(c) {
			//c.x, c.y, c.x2, c.y2, c.w, c.h
		}
	},
	error: function(msg, code) {
		this.file = null;
		this.ps.hide();
		alert('error: ' + msg + '\ncode: ' + code);
	},
	ps: {
		show: function() {
			_avatar.uploading = true;
			$('#avatarPhoto').html('');
			$('#saveButton').hide();
			$('#processIcon').show();
			$('#statusId').text(_avatar.language.uploading);
			$('#percentValue').text('0%');
			$('#percentBar').css({'width': '0%'});
			$('.processMask').show();
			$('.processBox').show();
		},
		hide: function() {
			$('#processIcon').hide();
			$('#statusId').text('Uploading ..');
			$('#percentValue').text('0%');
			$('#percentBar').css({'width': '0%'});
			$('.processMask').hide();
			$('.processBox').hide();
			_avatar.file = null;
			_avatar.uploading = false;
		}
	},
	doUpload: function() {
		if(this.file == null || typeof(this.file.id) == 'undefined') {
			return false;
		}
		this.ps.show();
		this.SWFUpload.setPostParams({});
		var params = this.fParams();
		for(var i in params) {
			this.SWFUpload.addPostParam(params[i]['name'], params[i]['value']);
		}
		this.SWFUpload.startUpload(this.file.id);
	},
	fParams: function() {
		var serializeData = this.setting.upload_form.serializeArray();
		var data = [];
		for(var i in serializeData) {
			data.push({name: serializeData[i]['name'], value: encodeURIComponent(serializeData[i]['value'])});
		}
		return data;
	},
	save: function() {
		var btn = $('#saveButton button[name=submit]');
		var btnHtml = btn.html();
		var _url = this.setting.upload_form.attr('action');
		var _data = [];
		var _params = this.fParams();
		for(var i in _params) {
			_data.push(_params[i]['name'] + '=' + _params[i]['value']);
		}
		$.ajax({type:'POST',dataType:'json',url:_url,data:_data.join('&'),success:function(json, status){
			try {
				if(json.status == 0) {
					throw json;
				}
				_avatar.redirect(btn);
			} catch (e) {
				_error(e.message, btnHtml);
			}
		}, error: function (req, msg, e) {
			_error(msg, btnHtml);
		}, beforeSend: function(req) {
			btn.html(_avatar.language.posting).attr('disabled', 'disabled');
		}, timeout: 30000});	
		return false;
		
		function _error(msg, btnHtml) {
			btn.html(btnHtml).removeAttr('disabled');
			alert(msg);
		}
	},
	update: function() {
		var btn = $('#updateButton button[name=submit]');
		var btnHtml = btn.html();
		var _url = this.setting.upload_form.attr('action');
		var _data = [];
		var _params = this.fParams();
		for(var i in _params) {
			_data.push(_params[i]['name'] + '=' + _params[i]['value']);
		}
		_data.push('submit=update');
		$.ajax({type:'POST',dataType:'json',url:_url,data:_data.join('&'),success:function(json, status){
			try {
				if(json.status == 0) {
					throw json;
				}
				_avatar.redirect(btn);
			} catch (e) {
				_error(e.message, btnHtml);
			}
		}, error: function (req, msg, e) {
			_error(msg, btnHtml);
		}, beforeSend: function(req) {
			btn.html(_avatar.language.posting).attr('disabled', 'disabled');
		}, timeout: 30000});	
		return false;
		
		function _error(msg, btnHtml) {
			btn.html(btnHtml).removeAttr('disabled');
			alert(msg);
		}
	},
	redirect: function(btn) {
		var referer = btn.parents('form').find('input[name=referer]').val();
		if(!referer || 
				referer.indexOf('login') > -1 || 
				referer.indexOf('signin') > -1 || 
				referer.indexOf('signup') > -1 || 
				referer.indexOf('oauth') > -1) referer = window.location.href;
		if(referer.indexOf('#') > -1) referer = referer.substring(0, referer.indexOf('#'));
		window.location.href = referer;
	}
};
